// pages/repair-form/repair-form.js
import api from "../../../utils/request"
Page({
    data: {
      formData: {
        houseId: "",
        houseAddress: "",
        repairTypeId: "",
        repairTypeName: "",
        repairArea: "",
        problemDescription:""
      },
      fileList: [],
      submitting: false,
      canSubmit: false,
  
      // 选择器状态
      showHouse: false,
      showRepairType: false,
      showArea: false,
  
      // 选项数据
      houseOptions: [
        { text: "城市花园1栋1单元1层101", value: "1" },
        { text: "城市花园1栋2单元2层201", value: "2" },
        { text: "城市花园2栋1单元3层301", value: "3" },
      ],
      repairTypeOptions: [],
      areaOptions: ["客厅", "卧室", "厨房", "卫生间", "阳台", "走廊", "其他"],
    },
  
    onLoad() {
      this.loadUserHouses()
      this.loadRepairTypes()
      this.checkCanSubmit()
    },
  
    // 加载用户房屋
    loadUserHouses() {
        wx.showLoading({ title: "加载中..." });
        api.get("/property/house/myHouses").then((res) => {
          if (res.code === 200) {
            const houseOptions = res.data.map((item) => ({
              text: `${item.communityName} ${item.buildingName} ${item.unitName} ${item.floor} ${item.doorNumber}`,
              value: item.roomId.toString(),
            }));
            this.setData({ houseOptions });
          } else {
            wx.showToast({ title: "加载房屋失败", icon: "none" });
          }
          wx.hideLoading();
        }).catch((err) => {
          console.error(err);
          wx.hideLoading();
          wx.showToast({ title: "加载房屋失败", icon: "none" });
        });
      },
  
    // pages/repair-form/repair-form.js
loadRepairTypes() {
    wx.showLoading({
      title: "加载中...",
    });
  
    api.get("/property/repairType/list").then((res) => {
      if (res.code === 200) {
        const repairTypeOptions = res.rows.map((item) => ({
          text: item.typeName,
          value: item.id,
        }));
  
        this.setData({
          repairTypeOptions,
        });
      } else {
        wx.showToast({
          title: "加载维修类型失败",
          icon: "none",
        });
      }
    }).catch((err) => {
      console.error(err);
      wx.showToast({
        title: "加载维修类型失败",
        icon: "none",
      });
    }).finally(() => {
      wx.hideLoading();
    });
  },
  
    // 字段变化处理
    onFieldChange(e) {
    console.log("事件对象:", e); // 打印整个事件对象
      const { field } = e.currentTarget.dataset
      const value = e.detail
  
      this.setData({
        [`formData.${field}`] : value,
      })
      console.log(this.data.formData.problemDescription)
  
      this.checkCanSubmit()
    },
  
    // 显示房屋选择器
    showHousePicker() {
      this.setData({ showHouse: true })
    },
  
    // 关闭房屋选择器
    closeHousePicker() {
      this.setData({ showHouse: false })
    },
  
    // 确认房屋选择
    onHouseConfirm(e) {
      const { value, index } = e.detail
      const selectedHouse = this.data.houseOptions[index]
  
      this.setData({
        "formData.houseId": selectedHouse.value,
        "formData.houseAddress": selectedHouse.text,
        showHouse: false,
      })
  
      this.checkCanSubmit()
    },
  
    // 显示维修类型选择器
    showRepairTypePicker() {
      this.setData({ showRepairType: true })
    },
  
    // 关闭维修类型选择器
    closeRepairTypePicker() {
      this.setData({ showRepairType: false })
    },
  
    // 确认维修类型选择
    onRepairTypeConfirm(e) {
      const { value, index } = e.detail
      const selectedType = this.data.repairTypeOptions[index]
  
      this.setData({
        "formData.repairTypeId": selectedType.value,
        "formData.repairTypeName": selectedType.text,
        showRepairType: false,
      })
  
      this.checkCanSubmit()
    },
  
    // 显示报修区域选择器
    showAreaPicker() {
      this.setData({ showArea: true })
    },
  
    // 关闭报修区域选择器
    closeAreaPicker() {
      this.setData({ showArea: false })
    },
  
    // 确认报修区域选择
    onAreaConfirm(e) {
      const { value } = e.detail
  
      this.setData({
        "formData.repairArea": value,
        showArea: false,
      })
  
      this.checkCanSubmit()
    },
  
    // 上传图片后
    onAfterRead(e) {
      const { file } = e.detail
      const { fileList = [] } = this.data
  
      // 模拟上传
      const uploadTask = fileList.concat(
        file.map((item) => ({
          ...item,
          url: item.url || item.path,
          name: "问题图片",
          isImage: true,
        })),
      )
  
      this.setData({ fileList: uploadTask })
    },
  
    // 删除图片
    onDeleteFile(e) {
      const { index } = e.detail
      const { fileList } = this.data
      fileList.splice(index, 1)
      this.setData({ fileList })
    },
  
    // 检查是否可以提交
    checkCanSubmit() {
      const { formData } = this.data
      const required = ["houseId", "repairTypeId", "repairArea","problemDescription"]
  
      const isFormValid = required.every((field) => {
        if (field === "problemDescription") {
          return formData[field] && formData[field].trim().length >= 10
        }
        return formData[field] && formData[field].trim()
      })
  
      this.setData({
        canSubmit: isFormValid,
      })
    },
  
    // 提交表单
    onSubmit() {
        if (!this.data.canSubmit) {
          wx.showToast({
            title: "请完善必填信息",
            icon: "none",
          });
          return;
        }
      
        this.setData({ submitting: true });
      
        const { formData, fileList } = this.data;
      
        // 调用 API 提交表单
        api.post("/property/repairRequest", formData).then((res) => {
          if (res.code === 200) {
            // 提交成功
            wx.showToast({
              title: "提交成功",
              icon: "success",
            });
      
            setTimeout(() => {
              wx.navigateBack(); // 返回上一页
            }, 1500);
          } else {
            // 提交失败
            wx.showToast({
              title: res.msg || "提交失败",
              icon: "none",
            });
          }
        }).catch((err) => {
          console.error(err);
          wx.showToast({
            title: "提交失败，请稍后再试",
            icon: "none",
          });
        }).finally(() => {
          this.setData({ submitting: false });
        });
      },
  })
  